<script>
	import {
		mapState,
		mapActions,
		mapMutations
	} from "vuex"
	import $store from "@/store/index.js"
	export default {
		data() {
			return {
				timer: null,
				travelTimer: null,
				orderTimer: null,
				lockTap: false,
				resolvePrivacyAuthorization: null
			}
		},
		async mounted() {
			// #ifdef H5
			if (window.location.href.indexOf('?#') < 0 && window.location.href.indexOf('state=STATE') < 0) {
				window.location.href = window.location.href.replace("#", "?#")
			}
			if (typeof window.entryUrl === 'undefined' || window.entryUrl === '') {
				window.entryUrl = window.location.href.split('#')[0]
			}
			// #endif
		},
		async onLaunch() {
			console.log("onLaunch----")
			// #ifndef H5
			let that = this
			uni.onLocationChange((res) => {
				let {
					latitude: lat,
					longitude: lng
				} = res
				console.log(res, "====onLocationChange")
				that.toChangeLocation({
					lat,
					lng
				})
			})
			// #endif
			let sysheight = uni.getSystemInfoSync().windowHeight
			this.updateConfigItem({
				key: 'sysheight',
				val: sysheight
			})

			let configInfo = uni.getStorageSync('configInfo') || ''
			if (configInfo) {
				this.updateConfigItem({
					key: 'configInfo',
					val: configInfo
				})
			}
			let isGzhLogin = uni.getStorageSync('isGzhLogin') || false
			this.updateUserItem({
				key: 'isGzhLogin',
				val: isGzhLogin
			})
			let arr = ['userInfo', 'autograph', 'city_info', 'auth_location', 'location', 'changeAddr', 'locaRefuse',
				'appLogin', 'loginType', 'loginPage', 'scanRecordId', 'is_register'
			]
			let {
				userInfo
			} = this
			let isReset = userInfo && userInfo.coach_id && !userInfo.id
			let {
				realtime_location = 0
			} = this.configInfo
			let isLogin = 0
			// #ifdef H5
			isLogin = window.location.href.indexOf('userA/pages/choose/index') > 0 || window.location.href.indexOf(
				'hotel/pages/list') > 0
			// #endif
			console.log(isLogin, "=======isLogin")
			arr.map(key => {
				let val = isReset ? '' : uni.getStorageSync(key) || ''
				if (key == 'userInfo' && !val) {
					val = {}
				}
				if (key == 'locaRefuse') {
					// #ifdef APP-PLUS
					val = val || false
					// #endif
					// #ifndef APP-PLUS
					val = true
					// #endif
				}
				if (realtime_location && !isLogin) {
					if (key == 'city_info') {
						val = {}
					}
					if (key == 'changeAddr') {
						val = false
					}
				}
				this.updateUserItem({
					key,
					val
				})
				// #ifdef APP-PLUS
				if (key == 'userInfo') {
					this.updateUserItem({
						key: 'isShowLogin',
						val: val && val.id ? false : true
					})
				}
				// #endif
			})
			this.getConfigInfo()
			// #ifdef MP-WEIXIN
			this.getPrivacySetting()
			// #endif  
		},
		async onShow(options) {
			const {
				referrerInfo = {},
					scene
			} = options || {};
			/* 判断是否从腾讯云E证通返回 */
			const {
				appId
			} = referrerInfo
			if (scene === 1038 && appId === 'wxa0a9f6f0154bbe7d') {
				const {
					extraData
				} = referrerInfo;
				if (extraData) {
					const {
						token,
						verifyDone
					} = extraData;
					// console.log(token, verifyDone)
					if (verifyDone) {
						console.log('核身完成');
						this.$api.technician.faceCallBack({
							eid_token: token
						})
						this.$util.goUrl({
							url: 1,
							openType: 'navigateBack'
						})
					}
				}
				return
			}
			// #ifdef MP-WEIXIN
			// console.log("来了1")
			wx.onNeedPrivacyAuthorization((resolve, eventInfo) => {
				console.log(resolve, 'resolve')
				this.resolvePrivacyAuthorization = resolve
			})
			// console.log("来了2")
			wx.requirePrivacyAuthorize({ //该接口请求隐私协议，会自动触发上边的wx.onNeedPrivacyAuthorization
				success: (suc) => {
					// console.log(suc, 'suc')
				},
				fail: (fail) => {}
			})
			// #endif
			// console.log("来了3")
			let {
				coach_travel_order_id
			} = this
			this.updateOrderItem({
				key: 'coach_travel_order_id',
				val: coach_travel_order_id
			})
			// #ifdef APP-PLUS
			uni.onNetworkStatusChange((res) => {
				let {
					isConnected
				} = res
				if (!isConnected) {
					let methodArr = ['updateServiceItem', 'updateTechnicianItem', 'updateMapItem',
						'updateDynamicItem', 'updateShopstoreItem', 'updateOrderItem'
					]
					methodArr.map(item => {
						$store.commit(item, {
							key: 'pageActive',
							val: false
						})
					})
				}
			})
			// #endif
			let time = 0
			// #ifdef H5
			time = 4000
			// #endif
			setTimeout(() => {
				let isStatus = true
				// #ifdef MP-WEIXIN-COACH || H5-COACH
				isStatus = false
				// #endif
				// #ifdef APP-PLUS
				isStatus = this.is_app_user ? true : false
				// #endif
				console.log(isStatus, "=====isStatus")
				if (isStatus) {
					this.getUserCoachStatus()
				}
				// #ifndef H5
				this.timerInit()
				// #endif
			}, time)
		},
		async onHide() {
			// #ifdef H5
			this.toHidePage()
			// #endif
			// #ifdef MP-WEIXIN
			uni.startLocationUpdateBackground({
				complete: msg => console.log(`startLocationUpdateBackground API complete`, msg)
			})
			// #endif
			if (this.coach_travel_order_id) {
				this.toAddCoachTravel()
			}
		},
		// #ifdef H5
		destroyed() {
			// #endif
			// #ifndef H5
			onUnload() {
					// #endif
					if (this.timer) clearInterval(this.timer)
					if (this.travelTimer) clearInterval(this.travelTimer)
					if (this.orderTimer) clearInterval(this.orderTimer)
				},
				watch: {
					resolvePrivacy(newval, oldval) {
						if (newval && this.resolvePrivacyAuthorization) {
							// #ifdef MP-WEIXIN
							this.resolvePrivacyAuthorization(newval)
							// #endif
						}
					},
					'configInfo.attendant_name'(newVal, oldVal) {
						if (newVal) {
							this.mergeLocaleMessage('attendant_name')
						}
					},
					'configInfo.reseller_menu_name'(newVal, oldVal) {
						if (newVal) {
							this.mergeLocaleMessage('reseller_menu_name')
						}
					},
					'configInfo.broker_menu_name'(newVal, oldVal) {
						if (newVal) {
							this.mergeLocaleMessage('broker_menu_name')
						}
					},
					'configInfo.channel_menu_name'(newVal, oldVal) {
						if (newVal) {
							this.mergeLocaleMessage('channel_menu_name')
						}
					},
					'configInfo.agent_default_name'(newVal, oldVal) {
						if (newVal) {
							this.mergeLocaleMessage('agent_default_name')
						}
					},
					'configInfo.life_text'(newVal, oldVal) {
						if (newVal) {
							this.mergeLocaleMessage('life_text')
						}
					},
					'configInfo.material_text'(newVal, oldVal) {
						if (newVal) {
							this.mergeLocaleMessage('material_text')
						}
					},
					// #ifdef H5
					isChangeCoachLoca(newVal, oldVal) {
						if (newVal) {
							setTimeout(() => {
								this.toHidePage(1)
							}, 3000)
						}
					},
					// #endif
					// // #ifdef APP-PLUS
					// isUtilLoca(newVal, oldVal) {
					// 	let {
					// 		status = 0,
					// 			coach_position = 0,
					// 			auto_coach_position = 0
					// 	} = this.userCoachStatus
					// 	if (status == 2 && auto_coach_position) {
					// 		let cur = newVal ? 0 : 1
					// 		let userCoachStatus = Object.assign({}, this.$util.deepCopy(this.userCoachStatus), {
					// 			coach_position: cur
					// 		})
					// 		if (!newVal) {
					// 			this.timerInit()
					// 		}
					// 		this.updateUserItem({
					// 			key: 'userCoachStatus',
					// 			val: userCoachStatus
					// 		})
					// 	}
					// },
					// // #endif
					// #ifndef H5
					userCoachStatus(newVal, oldVal) {
						let {
							status = 0,
								coach_position = 0,
						} = newVal
						if (status == 2) {
							if (!this.timer || coach_position) {
								this.timerInit()
							}
							let locationChange = coach_position ? true : false
							this.updateUserItem({
								key: 'locationChange',
								val: locationChange
							})
							// #ifdef APP-PLUS
							if (coach_position) {
								this.updateUserItem({
									key: 'locationChange',
									val: false
								})
								setTimeout(() => {
									this.updateUserItem({
										key: 'locationChange',
										val: true
									})
								}, 50)
							} else {
								setTimeout(() => {
									this.updateUserItem({
										key: 'locationChange',
										val: locationChange
									})
								}, 50)
							}
							// #endif
						} else {
							if (this.timer) clearInterval(this.timer)
							this.updateUserItem({
								key: 'locationChange',
								val: false
							})
						}
					},
					locationChange(newVal, oldVal) {
						if (newVal) {
							uni.startLocationUpdate({
								complete: msg => console.log(`startLocationUpdate API complete`, msg)
							})
							// #ifdef MP-WEIXIN
							uni.startLocationUpdateBackground({
								complete: msg => console.log(`startLocationUpdateBackground API complete`, msg)
							})
							// #endif
						} else {
							uni.stopLocationUpdate({
								complete: msg => console.log(`stopLocationUpdate API complete`, msg)
							})
						}
					},
					// #endif
					changeAddr(newval, oldval) {
						console.log(newval, this.configInfo.realtime_location, "=====changeAddr")
						if (!newval && this.configInfo.realtime_location) {
							let val = Object.assign({}, $store.state.technician.param, {
								city_id: 0
							})
							this.updateTechnicianItem({
								key: 'param',
								val
							})
							let city_info = Object.assign({}, this.city_info, {
								id: 0
							})
							this.updateUserItem({
								key: 'city_info',
								val: city_info
							})
						}
					},
					coach_travel_order_id(newVal, oldVal) {
						if (newVal) {
							this.toAddCoachTravel()
						}
					},
					coach_travel_arrive_id(newVal, oldVal) {
						if (this.travelTimer) clearInterval(this.travelTimer)
						if (newVal) {
							this.updateOrderItem({
								key: 'coach_travel_order_id',
								val: 0
							})
							this.toConfirmAddCoachTravel(newVal)
						}
					},
					order_unix_list(newVal, oldVal) {
						if (this.orderTimer) clearInterval(this.orderTimer)
						if (newVal && newVal.length > 0) {
							this.toOrderUnix(newVal)
						}
					}
				},
				computed: mapState({
					configInfo: state => state.config.configInfo,
					old_attendant_name: state => state.config.old_attendant_name,
					old_reseller_menu_name: state => state.config.old_reseller_menu_name,
					old_broker_menu_name: state => state.config.old_broker_menu_name,
					old_channel_menu_name: state => state.config.old_channel_menu_name,
					old_agent_default_name: state => state.config.old_agent_default_name,
					old_life_text: state => state.config.old_life_text,
					old_material_text: state => state.config.old_material_text,
					coach_travel_order_id: state => state.order.coach_travel_order_id,
					order_unix_list: state => state.order.order_unix_list,
					resolvePrivacy: state => state.user.resolvePrivacy
				}),
				methods: {
					...mapActions(['getConfigInfo', 'getUserInfo', 'getUserCoachStatus', 'getPrivacySetting',
						'toPlayAudio'
					]),
					...mapMutations(['updateUserItem', 'updateTechnicianItem', 'updateOrderItem', 'updateConfigItem']),
					// #ifndef H5
					timerInit() {
						if (this.timer) clearInterval(this.timer)
						this.timer = setInterval(() => {
							let {
								unix = 0
							} = this.changeOnAddr
							let cur_unix = this.$util.DateToUnix(this.$util.formatTime(new Date(), 'YY-M-D h:m:s'))
							if (!unix || (unix && (cur_unix - unix >= 3))) {
								let val = this.$util.deepCopy(this.userCoachStatus)
								val.unix = cur_unix
								this.updateUserItem({
									key: 'userCoachStatus',
									val: val
								})
							}
						}, 20000)
					},
					async toChangeLocation(param) {
						let {
							lat,
							lng
						} = param
						let {
							status: coach_status = 0,
							coach_position = 0,
							lat: coach_lat,
							lng: coach_lng,
						} = this.userCoachStatus
						if (coach_position && coach_status == 2) {
							let distance = this.$util.getDistance(lat, lng, coach_lat, coach_lng)
							let changeOnAddr = Object.assign({}, param, {
								unix: this.$util.DateToUnix(this.$util.formatTime(new Date(), 'YY-M-D h:m:s')),
								distance
							})
							this.updateUserItem({
								key: 'changeOnAddr',
								val: changeOnAddr
							})
							let max = 100
							// console.log("===distance===", distance, max)
							if (distance * 1 >= max) {
								this.$util.updateCoachAddr({
									lat,
									lng,
									address: ''
								})
							}
						}
					},
					// #endif
					async toHidePage(isChange = 0) {
						let {
							status = 0,
								coach_position = 0
						} = this.userCoachStatus
						let {
							auth_location
						} = this
						if (auth_location && (isChange || (coach_position && status == 2 && !this.isUtilLoca))) {
							this.$util.getCoachUtilLoca()
							if (isChange) {
								this.updateUserItem({
									key: 'isChangeCoachLoca',
									val: false
								})
							}
						}
					},
					// 轨迹
					async toAddCoachTravel() {
						let {
							coach_travel_order_id
						} = this
						let {
							coachtravel
						} = this.configInfo.plugAuth
						let {
							id: uid
						} = this.userInfo
						let {
							status: coach_status = 0,
						} = this.userCoachStatus
						if (this.travelTimer) clearInterval(this.travelTimer)
						if (coachtravel && coach_travel_order_id && uid && coach_status == 2) {
							this.toConfirmAddCoachTravel(coach_travel_order_id)
							this.travelTimer = setInterval(() => {
								this.toConfirmAddCoachTravel(coach_travel_order_id)
							}, 5000)
						}
					},
					async toConfirmAddCoachTravel(order_id) {
						if (!this.isUtilLoca && this.auth_location) {
							let {
								lat,
								lng,
								isIp = true
							} = await this.$util.getCoachUtilLoca(false)
							if (lat && lng && !isIp) {
								try {
									this.$api.technician.coachTrajectoryAdd({
										order_id,
										text: {
											lat,
											lng,
											address: ''
										}
									})
								} catch (e) {

								}
							}
						}
					},
					async toOrderUnix(list) {
						this.orderTimer = setInterval(() => {
							let count_down = list.filter(item => {
								let unix = Math.ceil((item.start_service_time_unix * 1000 - new Date()
									.getTime()) / 1000)
								return unix == 300
							})
							let end = list.filter(item => {
								let unix = Math.ceil((item.start_service_time_unix * 1000 - new Date()
									.getTime()) / 1000)
								return unix == 0
							})
							let val = list.filter(item => {
								let unix = Math.ceil((item.start_service_time_unix * 1000 - new Date()
									.getTime()) / 1000)
								return unix > 0
							})
							if (count_down.length > 0) {
								this.toPlayAudio({
									key: 'countdown_voice'
								})
							}
							if (end.length > 0) {
								this.toPlayAudio({
									key: 'service_end_recording'
								})
							}
							if (val.length !== list.length) {
								this.updateOrderItem({
									key: 'order_unix_list',
									val
								})
							}
							if (val.length === 0) {
								clearInterval(this.orderTimer)
							}
						}, 1000)
					},
					async mergeLocaleMessage(key) {
						let zh = JSON.parse(JSON.stringify(this.$i18n.messages.zh))
						let oldKey = `old_${key}`
						let name = this.configInfo[key]
						let oldName = this[oldKey]
						let reg = new RegExp(oldName, 'g')
						for (let i in zh.action) {
							if (zh.action[i].includes(oldName)) {
								zh.action[i] = zh.action[i].replace(reg, name)
							}
						}
						this.$i18n.mergeLocaleMessage('zh', zh)
						this.updateConfigItem({
							key: oldKey,
							val: name
						})
					}
				}
		}
</script>

<style lang="scss">
	@import "/styles/index.wxss";

	@font-face {
		font-family: "myFontNum";
		src: url('@/static/font/AlipayNumber-Regular.ttf') format('truetype');
	}

	/* #ifdef H5 */
	uni-page-head {
		display: none;
	}

	uni-toast {
		z-index: 10000;
	}

	/* #endif */
	.map-box .csssprite {
		border: 2px solid #fff !important;
		box-sizing: border-box;
		box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.1);
		border-radius: 50% !important;
	}

	.map-box a div .csssprite {
		display: none;
	}

	page {
		font-size: 28rpx;
		color: #222;
		line-height: 1.5;
		background: #F6F6F6;
		font-family: -apple-system-font, Helvetica Neue, Helvetica, sans-serif;
	}

	page>view {
		min-height: 100vh;
	}

	input::-webkit-input-placeholder {
		color: #A9A9A9;
	}

	input:-moz-placeholder {
		color: #A9A9A9;
	}

	input::-moz-placeholder {
		color: #A9A9A9;
	}

	input:-ms-input-placeholder {
		color: #A9A9A9;
	}

	view {
		box-sizing: border-box;
	}

	image {
		display: block;
	}

	.h5-image {
		background-position: center center;
		background-size: cover;
		background-repeat: no-repeat;
	}

	/*隐藏滚动条*/
	::-webkit-scrollbar {
		width: 0;
		height: 0;
		color: transparent;
	}

	/* #ifdef MP-BAIDU */
	.swan-button.swan-button-radius-ios {
		border-radius: 0;
	}

	/* #endif */
	/* 设置checkbox为圆形 */
	checkbox.round-checkbox .wx-checkbox-input,
	checkbox.round-checkbox .uni-checkbox-input {
	  border-radius: 50%; /* 设置为50%以实现圆形 */
	}
	
	/* 设置选中状态的背景色和边框色 */
	checkbox.round-checkbox[checked] .wx-checkbox-input,
	checkbox.round-checkbox.checked .uni-checkbox-input {
	  // background-color: #e54d42; /* 自定义选中背景色 */
	  // border-color: #e54d42; /* 自定义选中边框色 */
	}
</style>